/**
 * Express.js 数据持久化存储-MySQL示例
 */

//导入Express模块
const express= require("express");
//创建Express应用
const app=express();
//Express http服务端口
const port= 3001;
//导入MySQL数据访问模型
const db=require("./db/11_test_db");

//获取指定id的书籍信息
app.get("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("select * from books where id=?",[bookId]).then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
            console.error(error);
            res.end();
        });
    }

});

//获取书籍列表
app.get("/",function(req,res,next){
    db.query("select * from books").then(result=>{
        console.log(result);
        res.json(result);
    }).catch(error=>{
        console.error(error);
        res.end();
    });

});

//新增书籍列表
app.post("/",function(req,res,next){
        db.query("INSERT INTO books (title,description) VALUES(?,?)",[req.query.title,req.query.description]).then(result=>{
            console.log(result);
            res.json(result);
        }).catch(error=>{
            console.error(error);
            res.end();
        });

});

//修改书籍列表
app.use(express.json()); //使用req.body.···
//Content-Type: application/json
// {
//     "title":"修改测试标题",
//     "description":"作者:sa"
// }
app.put("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("update books set title=?,description=? where id=?",[req.body.title,req.body.description,bookId]).then(result=>{
            console.log(result.insertId);
            res.json(result);
        }).catch(error=>{
            console.error(error);
            res.end();
        });
    }

});

//删除
app.delete("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("delete from books where id=?",[bookId]).then(result=>{
            console.log(result.insertId);
            res.json(result);
        }).catch(error=>{
            console.error(error);
            res.end();
        });
    }

});

//启动Express服务
app.listen(port, function(){
    console.log(`MyApp访问地址：http://127.0.0.1:${port}`);
});
